#
#  Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
#

import logging
import time
from minio import Minio
from minio.error import S3Error
from io import BytesIO
from rag import settings
from rag.utils import singleton


# 使用singleton装饰器确保该类在整个应用中只有一个实例，用于封装MinIO操作
@singleton
class RAGFlowMinio:
    # 初始化方法，创建连接对象并调用__open__建立连接
    def __init__(self):
        self.conn = None
        self.__open__()

    # 打开或重新建立MinIO连接的方法
    def __open__(self):
        try:
            # 如果已有连接，先关闭旧连接
            if self.conn:
                self.__close__()
        except Exception:
            pass

        try:
            # 建立新的MinIO连接
            self.conn = Minio(settings.MINIO["host"],
                              access_key=settings.MINIO["user"],
                              secret_key=settings.MINIO["password"],
                              secure=False
                              )
        except Exception:
            # 连接失败时记录异常日志
            logging.exception(
                "Fail to connect %s " % settings.MINIO["host"])

    # 关闭当前MinIO连接的方法
    def __close__(self):
        del self.conn
        self.conn = None

    # 健康检查方法，测试MinIO是否正常工作
    def health(self):
        bucket, fnm, binary = "txtxtxtxt1", "txtxtxtxt1", b"_t@@@1"
        # 如果测试bucket不存在则创建
        if not self.conn.bucket_exists(bucket):
            self.conn.make_bucket(bucket)
        # 上传一个测试对象并返回结果
        r = self.conn.put_object(bucket, fnm,
                                 BytesIO(binary),
                                 len(binary)
                                 )
        return r

    # 向指定bucket上传文件对象，最多尝试3次
    def put(self, bucket, fnm, binary):
        for _ in range(3):
            try:
                # 如果目标bucket不存在则创建
                if not self.conn.bucket_exists(bucket):
                    self.conn.make_bucket(bucket)

                # 上传对象并返回结果
                r = self.conn.put_object(bucket, fnm,
                                         BytesIO(binary),
                                         len(binary)
                                         )
                return r
            except Exception:
                # 异常处理并重试，每次失败后重新连接MinIO并等待1秒
                logging.exception(f"Fail to put {bucket}/{fnm}:")
                self.__open__()
                time.sleep(1)

    # 删除指定bucket中的某个对象
    def rm(self, bucket, fnm):
        try:
            # 调用remove_object删除对象
            self.conn.remove_object(bucket, fnm)
        except Exception:
            # 删除失败时记录异常日志
            logging.exception(f"Fail to remove {bucket}/{fnm}:")

    # 获取指定bucket中的某个对象的内容
    def get(self, bucket, filename):
        for _ in range(1):
            try:
                # 获取对象并读取内容
                r = self.conn.get_object(bucket, filename)
                return r.read()
            except Exception:
                # 出现异常时重新连接并等待1秒
                logging.exception(f"Fail to get {bucket}/{filename}")
                self.__open__()
                time.sleep(1)
        return

    # 判断指定的bucket和对象是否存在
    def obj_exist(self, bucket, filename):
        try:
            # 如果bucket不存在直接返回False
            if not self.conn.bucket_exists(bucket):
                return False
            # 检查对象是否存在
            if self.conn.stat_object(bucket, filename):
                return True
            else:
                return False
        except S3Error as e:
            # 捕获S3错误并判断类型
            if e.code in ["NoSuchKey", "NoSuchBucket", "ResourceNotFound"]:
                return False
        except Exception:
            # 其他异常记录日志并返回False
            logging.exception(f"obj_exist {bucket}/{filename} got exception")
            return False

    # 获取预签名URL用于下载指定对象
    def get_presigned_url(self, bucket, fnm, expires):
        for _ in range(10):
            try:
                # 生成带有效期的GET请求预签名URL
                return self.conn.get_presigned_url("GET", bucket, fnm, expires)
            except Exception:
                # 失败时记录日志、重新连接并等待1秒
                logging.exception(f"Fail to get_presigned {bucket}/{fnm}:")
                self.__open__()
                time.sleep(1)
        return

